package com.quanshu.exchange.ui.gui.message.chat.redpackage;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.quanshu.exchange.R;
import com.quanshu.exchange.support.api.UserInterface;
import com.quanshu.exchange.support.config.Config;
import com.quanshu.exchange.support.entity.tmp.TmpStringData;
import com.quanshu.exchange.support.net.ApiException;
import com.quanshu.exchange.support.net.BaseResponse;
import com.quanshu.exchange.support.net.core.BaseObserver;
import com.quanshu.exchange.support.net.core.BaseTransformer;
import com.quanshu.exchange.support.net.core.NetClient;
import com.quanshu.exchange.support.utils.AppUtils;
import com.quanshu.exchange.support.utils.CashierInputFilter;
import com.quanshu.exchange.support.utils.CheckUtil;
import com.quanshu.exchange.support.utils.RxViewHelper;
import com.quanshu.exchange.ui.base.BaseActivity;
import com.quanshu.exchange.ui.gui.profile.SetPayPasswordActivity;

import butterknife.BindView;
import butterknife.ButterKnife;

public class LuckyRedPackageActivity extends BaseActivity {

    @BindView(R.id.back)
    LinearLayout back;
    @BindView(R.id.sum_points_edit)
    EditText sumPointsEdit;
    @BindView(R.id.red_package_num)
    EditText redPackageNum;
    @BindView(R.id.sum_member_nums)
    TextView sumMemberNums;
    @BindView(R.id.red_package_name)
    EditText redPackageName;
    @BindView(R.id.ok_btn)
    Button okBtn;

    private String sumPoints;
    private String memberNums;
    private String name;
    private String sumMembers;
    private String destId;

    private DialogCheckPayPwd checkPayPwdDialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_create_lucky_red_package);
        ButterKnife.bind(this);
        initIntent();
        initView();
        initListener();

    }

    private void initIntent() {
        sumMembers = getIntent().getStringExtra("sumMembers");
        destId = getIntent().getStringExtra("destId");
    }

    private void initView() {
        CashierInputFilter[] filters = {new CashierInputFilter()};
        sumPointsEdit.setFilters(filters);

        if (sumMembers != null) {
            sumMemberNums.setText("本群共 " + sumMembers + " 人");
        }
    }

    private void initListener() {

        RxViewHelper.getInstance().clicks(back, aVoid -> finish());

        sumPointsEdit.addTextChangedListener(new MyTextWatcher());
        redPackageNum.addTextChangedListener(new MyTextWatcher());
        redPackageName.addTextChangedListener(new MyTextWatcher());

        RxViewHelper.getInstance().clicks(okBtn, aVoid -> clickOkBtn());

    }

    private void clickOkBtn() {

        checkPayPwdDialog = new DialogCheckPayPwd(this);
        checkPayPwdDialog.show();
        checkPayPwdDialog.reset();
        checkPayPwdDialog.setPointsNumText(sumPoints);
        checkPayPwdDialog.getOkSubject().subscribe(str -> doCheck(str));

    }

    private void doCheck(String str) {

        NetClient.getInstance()
                .getNetService(UserInterface.class)
                .createRedPackage(AppUtils.getSignParams(currentUser.getMemberid(), "2", "2",
                        sumPoints, memberNums, destId, str, name), currentUser.getMemberid(), "2", "2",
                        sumPoints, memberNums, destId, str, name)
                .compose(new BaseTransformer<>(this))
                .subscribe(new BaseObserver<BaseResponse<TmpStringData>>() {

                    @Override
                    public void onSuccess(BaseResponse<TmpStringData> response) {
                        if (checkPayPwdDialog != null) {
                            checkPayPwdDialog.reset();
                            checkPayPwdDialog.cancel();
                        }
                        Intent intent = getIntent();
                        intent.putExtra("redPackageId", response.getInfo().getRed_id());
                        intent.putExtra("redPackageName", name);
                        setResult(RESULT_OK, intent);
                        finish();
                    }

                    @Override
                    public void onFailure(Throwable e) {
                        super.onFailure(e);
                        if (checkPayPwdDialog != null) {
                            checkPayPwdDialog.reset();
                            checkPayPwdDialog.cancel();
                        }
                        ApiException apiException = (ApiException) e;
                        // 如果返回未设置交易密码
                        if (apiException.getCode() == 1005) {
                            Intent intent = new Intent(LuckyRedPackageActivity.this, SetPayPasswordActivity.class);
                            intent.putExtra("setPwd", true);
                            startActivityForResult(intent, 0x01);
                        }
                    }
                });
    }

    private class MyTextWatcher implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void afterTextChanged(Editable editable) {

            sumPoints = sumPointsEdit.getText().toString();
            memberNums = redPackageNum.getText().toString();
            name = redPackageName.getText().toString();

            if (CheckUtil.isValidate(sumPoints, memberNums)) {
                okBtn.setEnabled(true);
            } else {
                okBtn.setEnabled(false);
            }
            if (name == null || name.length() < 1) {
                name = Config.DEFAULT_RED_PACKAGE_REMARK;
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 0x01) {

            }
        }
    }
}
